package com.frog.service.friend.service.msgchat;

import com.frog.framework.cache.redis.FrogRedisClient;
import com.frog.service.friend.enums.FriendRedisKeys;
import com.frog.service.friend.enums.RequestChatOperateEnum;
import com.frog.service.friend.mapper.RequestMsgStatusMapper;
import com.frog.service.friend.model.domain.RequestMsgStatusDO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.Column;
import java.lang.reflect.Field;
import java.util.*;


@Slf4j
@Service
public class RequestMsgChatServiceImpl implements RequestMsgChatService {

    @Autowired
    private RequestMsgStatusMapper requestMsgStatusMapper;
    @Autowired
    private FrogRedisClient redisClient;


    // api

    @Override
    public RequestMsgStatusDO selectRequestMsgChat(String id) {
        if (StringUtils.isBlank(id)) return null;
        try {
            return read(redisClient, RequestMsgStatusDO.class, FriendRedisKeys.USER_REQUEST_MSG_CHAT_STATUS_STRING, id);
        } catch (Exception exception) {
            log.error("select id=={}", id, exception);
            return null;
        }
    }

    @Override
    public boolean createRequestMsgChat(RequestMsgStatusDO requestMsgStatus) {
        if (requestMsgStatus == null || requestMsgStatus.getId() == null) return false;
        try {
            String id = String.valueOf(requestMsgStatus.getId());
            if (StringUtils.isBlank(requestMsgStatus.getChatStatus())) requestMsgStatus.setChatStatus("3");
            if (StringUtils.isBlank(requestMsgStatus.getResponseStatus())) requestMsgStatus.setResponseStatus("0");
            if (requestMsgStatus.getCreateTime() == null ) requestMsgStatus.setCreateTime(System.currentTimeMillis());
            if (requestMsgStatus.getUpdateTime() == null ) requestMsgStatus.setUpdateTime(System.currentTimeMillis());
            return write(redisClient, requestMsgStatus, FriendRedisKeys.USER_REQUEST_MSG_CHAT_STATUS_STRING, id) != null;
        } catch (Exception exception) {
            log.error("create id=={}", requestMsgStatus.getId(), exception);
            return false;
        }
    }

    @Override
    public boolean operateRequestMsgChat(RequestMsgStatusDO r, RequestChatOperateEnum operateEnum) {
        try {
            Map<String, Object> m = new HashMap<>();
            String chatStatus = operateEnum == RequestChatOperateEnum.reject ? "0" : operateEnum == RequestChatOperateEnum.accept ? "2" : "3";
            m.put("chat_status", chatStatus);
            m.put("response_status", "1");
            m.put("update_time", System.currentTimeMillis());
            update(redisClient, RequestMsgStatusDO.class, m, FriendRedisKeys.USER_REQUEST_MSG_CHAT_STATUS_STRING, String.valueOf(r.getId()));
            return true;
        } catch (Exception exception) {
            log.error("operate id=={}", r.getId(), exception);
            return false;
        }
    }


    // redis

    /**
     * 写
     */
    @Override
    public Integer insertStorage(List<RequestMsgStatusDO> t) {
        if (t == null || t.isEmpty()) return 0;
        return requestMsgStatusMapper.insertBatch(t);
    }

    /**
     * 读
     */
    @Override
    public Map selectdStorageByKey(Object[]... keyArgs) {
        Map<Object[], RequestMsgStatusDO> respMap = new HashMap<>();
        if (keyArgs == null || keyArgs.length == 0) return respMap;

        List<RequestMsgStatusDO> paramsList = new ArrayList<>();
        Map<Long, Object[]> mapping = new HashMap<>();

        for (Object[] keyArg : keyArgs) {
            if (keyArg == null || keyArg.length == 0 || keyArg[0] == null) continue;
            Long id = Long.valueOf((String) keyArg[0]);
            paramsList.add(RequestMsgStatusDO.builder().id(id).build());
            mapping.put(id, keyArg);
            respMap.put(keyArg, new RequestMsgStatusDO());
        }
        if (paramsList.isEmpty()) return respMap;

        for (RequestMsgStatusDO r : paramsList) {
            try {
                RequestMsgStatusDO rq = requestMsgStatusMapper.select(r.getId());
                if (rq == null || rq.getId() == null) continue;
                Object[] keyArg = mapping.get(rq.getId());
                respMap.put(keyArg, rq);
            } catch (Exception e) {
                log.error("RequestMsgChatServiceImpl selectdStorageByKey id==={} e", keyArgs, e);
            }
        }
        return respMap;
    }

    /**
     * 改
     */
    @Override
    public boolean updateStorageByFields(Map<String, Object> map, Object... keyArgs) {
        if ((map == null || map.isEmpty()) || (keyArgs == null || keyArgs.length == 0)) return false;
        String id = String.valueOf(keyArgs[0]);
        return requestMsgStatusMapper.updateByField(id, map) != 0;
    }

    /**
     * 实体字段和数据库字段对应关系
     */
    @Override
    public Map<String, String> storageEntityMapping() {
        Map<String, String> fieldMappingMap = new HashMap<>();
        Field[] fields = RequestMsgStatusDO.class.getDeclaredFields();
        for (Field field : fields) {
            if (field == null) continue;
            Column annotation = field.getAnnotation(Column.class);
            if (annotation == null) continue;
            fieldMappingMap.put(annotation.name(), field.getName());
        }
        return fieldMappingMap;
    }

}